<template>
  <div class="user-management-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" :inline="true" size="default">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.role" placeholder="请选择角色" clearable style="width: 150px;">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.disabled" placeholder="请选择状态" clearable style="width: 150px;">
            <el-option label="启用" :value="false" />
            <el-option label="禁用" :value="true" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <el-button type="success" :icon="Plus" @click="handleAdd">新增用户</el-button>
          <el-button type="primary" :icon="Refresh" circle @click="fetchUserList" />
        </div>
      </template>
      <el-table
        v-loading="tableLoading"
        :data="filteredTableData"
        border
        style="width: 100%"
      >
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="full_name" label="姓名" min-width="120" />
        <el-table-column prop="role" label="角色" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.role === 'admin' ? 'danger' : 'info'">
              {{ row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="disabled" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.disabled ? 'danger' : 'success'">
              {{ row.disabled ? '禁用' : '启用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button 
                :type="row.disabled ? 'success' : 'warning'"
                size="small" 
                @click="handleToggleStatus(row)"
              >
                {{ row.disabled ? '启用' : '禁用' }}
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <user-form-dialog
      v-model:visible="formVisible"
      :form-data="formData"
      :is-edit="isEdit"
      @success="handleFormSuccess"
    />
    
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Plus } from '@element-plus/icons-vue';
import { getUserList, deleteUser, updateUser } from '@/api/user';
import UserFormDialog from './components/UserFormDialog.vue';

// 搜索表单
const searchFormRef = ref();
const searchForm = reactive({
  username: '',
  role: '',
  disabled: null as boolean | null
});

// 表格数据
const tableData = ref<any[]>([]);
const tableLoading = ref(false);

// 过滤后的表格数据
const filteredTableData = computed(() => {
  return tableData.value.filter(row => {
    const usernameMatch = searchForm.username ? 
      row.username.toLowerCase().includes(searchForm.username.toLowerCase()) : true;
    const roleMatch = searchForm.role ? 
      row.role === searchForm.role : true;
    const disabledMatch = searchForm.disabled !== null ? 
      row.disabled === searchForm.disabled : true;
    return usernameMatch && roleMatch && disabledMatch;
  });
});

// 表单相关
const formVisible = ref(false);
const formData = ref<any>({});
const isEdit = ref(false);

// 日期格式化函数
const formatDateTime = (dateString: string): string => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  if (isNaN(date.getTime())) return dateString;
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 获取用户列表
const fetchUserList = async () => {
  try {
    tableLoading.value = true;
    const res: any = await getUserList();
    
    if (res.code === 200) {
      tableData.value = res.data || [];
    } else {
      ElMessage.error(res.message || '获取用户列表失败');
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  } finally {
    tableLoading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  // 前端已经使用计算属性进行过滤，这里不需要额外操作
};

// 重置搜索条件
const handleReset = () => {
  searchFormRef.value?.resetFields();
};

// 新增用户
const handleAdd = () => {
  formData.value = {
    username: '',
    full_name: '',
    email: '',
    role: 'user',
    disabled: false,
    password: ''
  };
  isEdit.value = false;
  formVisible.value = true;
};

// 编辑用户
const handleEdit = (row: any) => {
  formData.value = { ...row };
  isEdit.value = true;
  formVisible.value = true;
};

// 表单提交成功回调
const handleFormSuccess = () => {
  formVisible.value = false;
  fetchUserList();
};

// 切换用户状态
const handleToggleStatus = async (row: any) => {
  try {
    const newStatus = !row.disabled;
    const statusText = newStatus ? '禁用' : '启用';
    
    ElMessageBox.confirm(`确认${statusText}用户"${row.username}"?`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const res: any = await updateUser(row._id, { disabled: newStatus });
      if (res.code === 200) {
        ElMessage.success(`${statusText}成功`);
        fetchUserList();
      } else {
        ElMessage.error(res.message || `${statusText}失败`);
      }
    });
  } catch (error) {
    console.error('更新用户状态失败:', error);
    ElMessage.error('更新用户状态失败');
  }
};

// 删除用户
const handleDelete = (row: any) => {
  try {
    ElMessageBox.confirm(`确认删除用户"${row.username}"?`, '删除提示', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const res: any = await deleteUser(row._id);
      if (res.code === 200) {
        ElMessage.success('删除成功');
        fetchUserList();
      } else {
        ElMessage.error(res.message || '删除失败');
      }
    }).catch(() => {
      ElMessage.info('已取消删除');
    });
  } catch (error) {
    console.error('删除用户失败:', error);
    ElMessage.error('删除用户失败');
  }
};

// 页面初始化
onMounted(() => {
  fetchUserList();
});
</script>

<style lang="scss" scoped>
.user-management-container {
  padding: 20px;

  .search-card {
    margin-bottom: 16px;
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style>